package com.finance.console.storage;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDAO {
    protected Connection conn;
    protected PreparedStatement pstmt;
    protected ResultSet rs;

    // 执行增删改（返回影响行数）
    protected int executeUpdate(String sql, Object... params) {
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            setParams(params); // 填充SQL参数
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("SQL执行失败", e);
        } finally {
            close(); // 关闭资源
        }
    }

    // 执行查询（需子类处理ResultSet）
    protected void executeQuery(String sql, Object... params) {
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            setParams(params);
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            throw new RuntimeException("SQL查询失败", e);
        }
    }

    // 填充SQL参数
    private void setParams(Object... params) throws SQLException {
        if (params == null || params.length == 0) {
            return;
        }
        for (int i = 0; i < params.length; i++) {
            pstmt.setObject(i + 1, params[i]);
        }
    }

    // 关闭资源
    protected void close() {
        try {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}